<template>
  <div class="message-send">
    <el-card>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="160px"
        style="max-width: 600px; margin: 0 auto"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入消息标题" />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="4" placeholder="请输入消息内容" />
        </el-form-item>

        <el-form-item label="接收人" prop="receiveUserNames">
          <el-select
            v-model="form.receiveUserNames"
            multiple
            filterable
            remote
            :remote-method="remoteMethod"
            placeholder="请输入用户名"
            clearable
          >
            <el-option
              v-for="user in userOptions"
              :key="user.value"
              :label="user.label"
              :value="user.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">发送</el-button>
          <el-button :disabled="loading" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import UserAPI from "@/api/system/user.api";
import { ElMessage } from "element-plus";

const formRef = ref();
const loading = ref(false);
const userOptions = ref<{ label: string; value: string }[]>([]);

const form = reactive({
  title: "",
  content: "",
  receiveUserNames: [] as string[],
});

const rules = {
  title: [{ required: true, message: "请输入消息标题", trigger: "blur" }],
  content: [{ required: true, message: "请输入消息内容", trigger: "blur" }],
  receiveUserNames: [{ required: true, message: "请选择接收人", trigger: "change" }],
};

const remoteMethod = async (query: string) => {
  if (query) {
    try {
      const [studentsRes, adminsRes] = await Promise.allSettled([
        UserAPI.getUserPage({ userName: query, role: 1, pageIndex: 1, pageSize: 10 }),
        UserAPI.getUserPage({ userName: query, role: 3, pageIndex: 1, pageSize: 10 }),
      ]);

      const allUsers: any[] = [];
      if (studentsRes.status === "fulfilled") {
        allUsers.push(...studentsRes.value.list);
      }
      if (adminsRes.status === "fulfilled") {
        allUsers.push(...adminsRes.value.list);
      }

      userOptions.value = allUsers.map((user: any) => ({
        label: user.userName,
        value: user.userName,
      }));
    } catch {
      userOptions.value = [];
    }
  } else {
    userOptions.value = [];
  }
};

async function handleSubmit() {
  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    loading.value = true;

    const ids: number[] = [];
    for (const name of form.receiveUserNames) {
      try {
        const res = await UserAPI.getUserPage({ userName: name, pageIndex: 1, pageSize: 1 });
        const user = res.list.find((u: any) => u.userName === name);
        if (user) {
          ids.push(user.id);
        } else {
          ElMessage.error(`用户 ${name} 不存在`);
          loading.value = false;
          return;
        }
      } catch {
        ElMessage.error(`获取用户 ${name} 信息失败`);
        loading.value = false;
        return;
      }
    }

    UserAPI.sendMessage({
      title: form.title,
      content: form.content,
      receiveUserIds: ids,
    })
      .then(() => {
        ElMessage.success("发送成功");
        handleReset();
      })
      .catch(() => {
        ElMessage.error("发送失败");
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

function handleReset() {
  form.title = "";
  form.content = "";
  form.receiveUserNames = [];
  formRef.value?.clearValidate();
}
</script>

<style scoped lang="scss">
.message-send {
  padding: 32px 0;
}
</style>
